import { defineStore } from 'pinia'
import { ref } from 'vue'
import { list, type PatientBo, type PatientResponse } from '@/api/system/patient'

export interface Patient {
  id: string
  name: string
  gender: '男' | '女'
  age: number
  phone: string
  idCard: string
  address: string
  emergencyContact: string
  emergencyPhone: string
  medicalHistory: string[]
  allergies: string[]
  bloodType: string
  height: number
  weight: number
  bmi: number
  registrationDate: string
  lastVisit: string
  status: '正常' | '住院' | '出院' | '死亡'
  doctorId: string
  departmentId: string
  diagnoses: string[]
  medications: string[]
  notes: string
  birth: string
  contact: string
  addressId: string
}

const transformApiPatientToPatient = (apiPatient: PatientResponse): Patient => {
  const { patient, medicalCaseList, users } = apiPatient
  
  const birth = new Date(patient.patientBirth)
  const age = new Date().getFullYear() - birth.getFullYear()
  
  const chiefComplaints = medicalCaseList.map(mc => mc.chiefComplaint)
  
  // 取第一个用户作为紧急联系人，如果有多个用户可以用逗号分隔
  const emergencyContact = users.length > 0 ? users[0].username : ''
  const emergencyPhone = users.length > 0 ? users[0].userContact : ''
  
  // 如果有多个用户，可以在备注中显示所有用户信息
  const userNotes = users.length > 1 
    ? `关联用户: ${users.map(u => `${u.username}(${u.userContact})`).join(', ')}` 
    : ''
  
  return {
    id: patient.patientId,
    name: patient.patientName,
    gender: patient.patientGender === 0 ? '女' : '男',
    age,
    phone: patient.patientContact,
    idCard: '',
    address: '',
    emergencyContact,
    emergencyPhone,
    medicalHistory: [],
    allergies: [],
    bloodType: '',
    height: 0,
    weight: 0,
    bmi: 0,
    registrationDate: '',
    lastVisit: medicalCaseList.length > 0 ? medicalCaseList[0].createdAt.split('T')[0] : '',
    status: '正常',
    doctorId: '',
    departmentId: medicalCaseList.length > 0 ? medicalCaseList[0].deptId : '',
    diagnoses: chiefComplaints,
    medications: [],
    notes: userNotes,
    birth: patient.patientBirth,
    contact: patient.patientContact,
    addressId: patient.addressId
  }
}

export const usePatientStore = defineStore('patient', () => {
  const patients = ref<Patient[]>([])
  const currentPatient = ref<Patient | null>(null)
  const searchQuery = ref('')
  const filterStatus = ref('')
  const loading = ref(false)

  const getPatients = async (params: Partial<PatientBo> = {}) => {
    loading.value = true
    try {
      const searchParams: PatientBo = {
        deptIds: params.deptIds || [],
        patientName: params.patientName,
        patientContact: params.patientContact
      }
      
      const response = await list(searchParams)
      
      if (response.code === 200) {
        patients.value = response.data.map(transformApiPatientToPatient)
      }
      
      return patients.value
    } catch (error) {
      console.error('获取患者列表失败:', error)
      return []
    } finally {
      loading.value = false
    }
  }

  // 根据ID获取患者
  const getPatientById = (id: string) => {
    return patients.value.find(p => p.id === id)
  }

  // 添加患者
  const addPatient = async (patient: Omit<Patient, 'id' | 'registrationDate'>) => {
    loading.value = true
    try {
      const newPatient: Patient = {
        ...patient,
        id: `P${Date.now()}`,
        registrationDate: new Date().toISOString().split('T')[0]
      }
      patients.value.unshift(newPatient)
      return newPatient
    } finally {
      loading.value = false
    }
  }

  // 更新患者信息
  const updatePatient = async (id: string, updates: Partial<Patient>) => {
    loading.value = true
    try {
      const index = patients.value.findIndex(p => p.id === id)
      if (index > -1) {
        patients.value[index] = { ...patients.value[index], ...updates }
        return patients.value[index]
      }
      throw new Error('患者不存在')
    } finally {
      loading.value = false
    }
  }

  // 删除患者
  const deletePatient = async (id: string) => {
    loading.value = true
    try {
      const index = patients.value.findIndex(p => p.id === id)
      if (index > -1) {
        patients.value.splice(index, 1)
        return true
      }
      return false
    } finally {
      loading.value = false
    }
  }

  const searchPatients = (query: string) => {
    searchQuery.value = query
    if (!query) return patients.value
    
    return patients.value.filter(patient => 
      patient.name.includes(query) ||
      patient.phone.includes(query) ||
      patient.contact.includes(query)
    )
  }

  const searchPatientsWithApi = async (query: string) => {
    if (!query.trim()) {
      return await getPatients()
    }
    
    const phonePattern = /^1[3-9]\d{9}$/
    if (phonePattern.test(query)) {
      return await getPatients({ patientContact: query })
    } else {
      return await getPatients({ patientName: query })
    }
  }

  // 按状态筛选
  const filterPatientsByStatus = (status: string) => {
    filterStatus.value = status
    if (!status) return patients.value
    
    return patients.value.filter(patient => patient.status === status)
  }

  // 计算BMI
  const calculateBMI = (height: number, weight: number) => {
    const heightInM = height / 100
    return Math.round((weight / (heightInM * heightInM)) * 10) / 10
  }

  // 获取统计数据
  const getPatientStats = () => {
    const total = patients.value.length
    const byStatus = patients.value.reduce((acc, patient) => {
      acc[patient.status] = (acc[patient.status] || 0) + 1
      return acc
    }, {} as Record<string, number>)
    
    const byGender = patients.value.reduce((acc, patient) => {
      acc[patient.gender] = (acc[patient.gender] || 0) + 1
      return acc
    }, {} as Record<string, number>)

    const averageAge = Math.round(
      patients.value.reduce((sum, patient) => sum + patient.age, 0) / total
    )

    return {
      total,
      byStatus,
      byGender,
      averageAge
    }
  }

  return {
    patients,
    currentPatient,
    searchQuery,
    filterStatus,
    loading,
    getPatients,
    getPatientById,
    addPatient,
    updatePatient,
    deletePatient,
    searchPatients,
    searchPatientsWithApi,
    filterPatientsByStatus,
    calculateBMI,
    getPatientStats
  }
}, {
  persist: {
    key: 'patient-store',
    storage: localStorage,
    paths: ['patients']
  }
})